import datetime
from xml.dom.minidom import parse
import xml.dom.minidom
import socket
import time
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
import xml.dom.minidom
import redis
from aibox.utils.aibox_tools import pd_save
from aibox.utils.logger import user_system_log
import pandas as pd

from bqtool.utils.attrdictkit import AttrDictKit


class UtcSignal(object):
    """
    连接socket消息服务器
    处理utc灯态数据
    """
    DIRECTION_DIC = {'1': '2_1', '2': '2_0', '3': '2_2', '4': '4_1', '5': '4_0', '6': '4_2',
                     '7': '1_1', '8': '1_0', '9': '1_2', '10': '3_1', '11': '3_0', '12': '3_2'}
    START_QUEUE_NAME = 'aibox:tsce_start'
    END_QUEUE_NAME = 'aibox:tsce_end'

    def __init__(self):
        self._config = AttrDictKit({'utc':{'ip':'127.0.0.1','port':60000}})
        self._executor = ThreadPoolExecutor(max_workers=10)
        pool = redis.ConnectionPool(host='127.0.0.1', decode_responses=True,
        port=6379, db=7, password=None)
        self._cache = redis.Redis(connection_pool=pool)
        self._que = Queue()
        self._data_str = ''

    def init_connect(self):
        """
        初始化连接
        需要注意断线后重连
        :return:
        """
        self._client = socket.socket()
        self._client.connect((self._config.utc.ip, self._config.utc.port))
        self.send('test')

    def send(self, xmls):
        """
        发送xml
        :param xmls:
        :return:
        """
        by = xmls.encode('gb2312')  # 转为字节数组
        try:
            self._client.send(by)
        except:
            self.init_connect()
            self._client.send(by)

    def recv(self, bufsize=1024):
        try:
            ret_bytes = self._client.recv(bufsize)
            if ret_bytes == b'':
                self.init_connect()
                ret_bytes = self._client.recv(bufsize)
        except Exception as e:
            print(e)
            self.init_connect()
            ret_bytes = self._client.recv(bufsize)
        return ret_bytes

    def readone(self):
        try:
            data = ''
            while True:
                ret_bytes = self.recv(1024)
                ret_str = ret_bytes.decode('gb2312', "ignore")
                self._data_str += ret_str
                if """</message>""" in self._data_str:
                    path = self._data_str.find("""</message>""")
                    data = self._data_str[0:path + 10]
                    self._data_str = self._data_str[path + 10:]
                    break
            self.get_xml_data(data)
        except Exception:
            user_system_log.exception('readone执行出错')
            return

    def readall(self):
        while True:
            time.sleep(0.1)
            self.readone()

    def deal_data(self):
        list = []
        while True:
            if not self._que.empty():
                data = self._que.get()
                list.append(data)
                if len(list) >= 25:
                    self.save_data(list)
                    list.clear()

    def save_data(self, list):
        df = pd.DataFrame(list, columns=['lcid', 'starttime', 'endtime',
                                         'direction', 'turn'])
        try:
            df.save('t_utc_greentime', self.mysql_conn)
        except Exception as e:
            user_system_log.exception('save_data执行出错')

    def get_xml_data(self, data):
        """
        处理接收到的数据
        :param data:
        :return:
        """
        try:
            print(data)
        except Exception:
            user_system_log.exception('get_xml_data执行出错')
            return

    def init_listen(self, lcid, utctype):
        listen_xml = f"""
                           <?xml version="1.0" encoding="GB2312"?>
                           <subscription System="ATMS" Ver="1.0">
                               <systemtype>UTC</systemtype>
                               <messagetype>NOTICE</messagetype>
                               <sourceIP></sourceIP>
                               <targetIP>{utctype}_{lcid}</targetIP>
                               <user>utc</user>
                               <password></password>
                           </subscription>
                           """
        start_xml = f"""
                           <?xml version="1.0" encoding="GB2312"?>
                           <message System="ATMS" Ver="1.0">
                               <systemtype>UTC</systemtype>
                               <messagetype>REQUEST</messagetype>
                               <sourceIP></sourceIP>
                               <targetIP>{utctype}</targetIP>
                               <user>utc</user>
                               <password></password>
                               <request>
                                   <type>SIGNALSTART</type>
                                   <id>{lcid}</id>
                               </request>
                           </message>"""
        self.send(listen_xml)
        self.send(start_xml)

    def start_signal(self):
        """
        初始化接收信号机灯态数据
        新开线程，持续运行
        :return:
        """
        self.init_connect()
        self.readall()
        # self._executor.submit(self.readall)
        # self._executor.submit(self.deal_data)

if __name__ == "__main__":
    print('start')
    xmls = """
    <?xml version="1.0" encoding="GB2312"?>
    <message System="ATMS" Ver="1.0">
        <systemtype>UTC</systemtype>
        <messagetype>REQUEST</messagetype>
        <sourceIP></sourceIP>
        <targetIP>MTC1032</targetIP>
        <user>utc</user>
        <password></password>
        <request>
            <type>BASEINFO</type>
            <id>537919593</id>
        </request>
    </message>
    """
    startxml = """
    <?xml version="1.0" encoding="GB2312"?>
    <message System="ATMS" Ver="1.0">
        <systemtype>UTC</systemtype>
        <messagetype>REQUEST</messagetype>
        <sourceIP></sourceIP>
        <targetIP>MTC1032</targetIP>
        <user>utc</user>
        <password></password>
    </message>
    """
    xstr = """
     <?xml version="1.0" encoding="GB2312"?>
<message System="ATMS" Ver="1.0">
    <systemtype>UTC</systemtype>
    <messagetype>REQUEST</messagetype>
    <sourceIP></sourceIP>
    <targetIP>MTC1032</targetIP>
    <user>utc</user>
    <password></password>
    <request>
        <type>SIGNALSTATUS</type>
        <id>537919593</id>
    </request>
</message>
    """

    # send(xstr)
    # readone()
    # send(startxml)

    notice = """
        <?xml version="1.0" encoding="GB2312"?>
    <subscription System="ATMS" Ver="1.0">
    <systemtype>UTC</systemtype>
    <messagetype>NOTICE</messagetype>
    <sourceIP></sourceIP>
    <targetIP>MTC1032</targetIP>
    <user>utc</user>
    <password></password>
    </subscription>"""
    notices = """
            <?xml version="1.0" encoding="GB2312"?>
        <subscription System="ATMS" Ver="1.0">
        <systemtype>UTC</systemtype>
        <messagetype>NOTICE</messagetype>
        <sourceIP></sourceIP>
        <targetIP>MTC2000_537919593</targetIP>
        <user>utc</user>
        <password></password>
        </subscription>"""
    nn = """
        <?xml version="1.0" encoding="GB2312"?>
    <message System="ATMS" Ver="1.0">
        <systemtype>UTC</systemtype>
        <messagetype>REQUEST</messagetype>
        <sourceIP></sourceIP>
        <targetIP>MTC2000</targetIP>
        <user>utc</user>
        <password></password>
        <request>
            <type>SIGNALSTART</type>
            <id>537919593</id>
        </request>
    </message>"""

    notices2 = """
                <?xml version="1.0" encoding="GB2312"?>
            <subscription System="ATMS" Ver="1.0">
            <systemtype>UTC</systemtype>
            <messagetype>NOTICE</messagetype>
            <sourceIP></sourceIP>
            <targetIP>MTC1032_537919612</targetIP>
            <user>utc</user>
            <password></password>
            </subscription>"""
    nn2 = """
            <?xml version="1.0" encoding="GB2312"?>
        <message System="ATMS" Ver="1.0">
            <systemtype>UTC</systemtype>
            <messagetype>REQUEST</messagetype>
            <sourceIP></sourceIP>
            <targetIP>MTC1032</targetIP>
            <user>utc</user>
            <password></password>
            <request>
                <type>SIGNALSTART</type>
                <id>537919612</id>
            </request>
        </message>"""
    signal = UtcSignal()
    signal.start_signal()
    # send(nn)

